<template>
  <div class="bill-detail-container">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button icon="ArrowLeft" type="text" @click="goBack">返回</el-button>
          <span class="header-title">账单详情</span>
          <div class="header-actions">
            <el-button 
              v-if="bill && (bill.status === 'UNPAID' || bill.status === 'OVERDUE')"
              type="primary" 
              size="small" 
              @click="handlePayBill"
              :loading="paymentLoading"
            >
              立即支付
            </el-button>
          </div>
        </div>
      </template>

      <el-skeleton :loading="loading" animated>
        <template #template>
          <div style="padding: 20px">
            <el-skeleton-item variant="text" style="width: 30%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 50%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 40%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 60%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 35%; margin-bottom: 15px" />
          </div>
        </template>

        <template #default>
          <div v-if="bill" class="bill-info">
            <div class="bill-header">
              <div class="bill-status">
                <el-tag :type="getBillStatusType(bill.status)" size="large">
                  {{ getBillStatusText(bill.status) }}
                </el-tag>
              </div>
              <div class="bill-amount">
                <span class="amount-label">账单金额</span>
                <span class="amount-value">¥{{ bill.amount }}</span>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">账单信息</div>
              <div class="info-row">
                <span class="info-label">账单编号：</span>
                <span>{{ bill.id }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">关联协商：</span>
                <span>
                  {{ bill.negotiationId }}
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="viewNegotiationDetail(bill.negotiationId)"
                  >
                    查看协商详情
                  </el-button>
                </span>
              </div>
              <div class="info-row">
                <span class="info-label">创建时间：</span>
                <span>{{ formatDateTime(bill.createdTime) }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">支付期限：</span>
                <span :class="{'overdue': isOverdue(bill.dueDate)}">
                  {{ formatDateTime(bill.dueDate) }}
                </span>
              </div>
              <div class="info-row" v-if="bill.paymentDate">
                <span class="info-label">支付时间：</span>
                <span>{{ formatDateTime(bill.paymentDate) }}</span>
              </div>
              <div class="info-row" v-if="bill.paymentMethod">
                <span class="info-label">支付方式：</span>
                <span>{{ getPaymentMethodText(bill.paymentMethod) }}</span>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">广告和设备信息</div>
              <div class="info-row">
                <span class="info-label">广告名称：</span>
                <span>{{ bill.advertisementName }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">广告主：</span>
                <span>{{ bill.advertiserName }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">设备主：</span>
                <span>{{ bill.deviceOwnerName }}</span>
              </div>
            </div>

            <div class="payment-section" v-if="bill.status === 'UNPAID'">
              <el-alert
                title="请在支付期限前完成支付，避免产生逾期记录影响信用"
                type="warning"
                :closable="false"
                show-icon
              />
              <div class="payment-action">
                <el-button 
                  type="primary" 
                  size="large" 
                  @click="handlePayBill"
                  :loading="paymentLoading"
                >
                  立即支付
                </el-button>
              </div>
            </div>

            <div class="payment-section" v-else-if="bill.status === 'PAID'">
              <el-alert
                title="账单已支付，感谢您的合作"
                type="success"
                :closable="false"
                show-icon
              />
            </div>

            <div class="payment-section" v-else-if="bill.status === 'OVERDUE'">
              <el-alert
                title="账单已逾期，请尽快支付，避免影响后续合作"
                type="error"
                :closable="false"
                show-icon
              />
              <div class="payment-action">
                <el-button 
                  type="danger" 
                  size="large" 
                  @click="handlePayBill"
                  :loading="paymentLoading"
                >
                  立即支付
                </el-button>
              </div>
            </div>
          </div>
          <el-empty v-else description="未找到账单信息"></el-empty>
        </template>
      </el-skeleton>
    </el-card>

    <!-- 支付选择对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="选择支付方式"
      width="500px"
      destroy-on-close
    >
      <div class="payment-dialog-content">
        <div class="payment-methods">
          <div 
            class="payment-method-item" 
            :class="{ active: selectedPaymentMethod === 'WECHAT' }"
            @click="selectedPaymentMethod = 'WECHAT'"
          >
            <div class="method-icon wechat">
              <i class="iconfont icon-wechat"></i>
            </div>
            <div class="method-name">微信支付</div>
          </div>
          <div 
            class="payment-method-item" 
            :class="{ active: selectedPaymentMethod === 'ALIPAY' }"
            @click="selectedPaymentMethod = 'ALIPAY'"
          >
            <div class="method-icon alipay">
              <i class="iconfont icon-alipay"></i>
            </div>
            <div class="method-name">支付宝支付</div>
          </div>
        </div>
        
        <div class="payment-amount">
          <div class="amount-title">支付金额</div>
          <div class="amount-value">¥{{ bill?.amount }}</div>
        </div>
        
        <div v-if="qrCodeUrl" class="qrcode-container">
          <div class="qrcode-title">
            {{ selectedPaymentMethod === 'WECHAT' ? '微信扫码支付' : '支付宝扫码支付' }}
          </div>
          <div class="qrcode">
            <img :src="qrCodeUrl" alt="支付二维码" />
          </div>
          <div class="qrcode-tip">
            请使用{{ selectedPaymentMethod === 'WECHAT' ? '微信' : '支付宝' }}扫描二维码完成支付
          </div>
          <!-- <div class="auto-pay-countdown" v-if="countdownSeconds > 0">
            <el-progress :percentage="(10 - countdownSeconds) * 10" :stroke-width="6" />
            <span class="countdown-text">模拟支付中...{{ countdownSeconds }}秒后自动完成</span>
          </div> -->
        </div>
        <div v-else class="qrcode-loading">
          <el-skeleton animated>
            <template #template>
              <div style="display: flex; justify-content: center; align-items: center;">
                <el-skeleton-item variant="image" style="width: 200px; height: 200px;" />
              </div>
            </template>
          </el-skeleton>
          <div class="loading-text">正在生成支付二维码...</div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { getBillDetail, generatePaymentQRCode, checkPaymentStatus, mockPaymentSuccess as mockApiSuccess } from '@/api/bill';

const route = useRoute();
const router = useRouter();
const billId = ref(route.params.id);
const bill = ref(null);
const loading = ref(true);
const paymentLoading = ref(false);
const paymentDialogVisible = ref(false);
const selectedPaymentMethod = ref('WECHAT');
const qrCodeUrl = ref('');
const paymentCheckInterval = ref(null);
const autoPayTimeout = ref(null);
const countdownSeconds = ref(0);
const countdownInterval = ref(null);

// 获取账单详情
const fetchBillDetail = async () => {
  try {
    loading.value = true;
    const res = await getBillDetail(billId.value);
    console.log('账单详情', res);
    if (res.data.code === 200) {
      bill.value = res.data.data;
    } else {
      ElMessage.error(res.data.message || '获取账单详情失败');
    }
  } catch (error) {
    console.error('获取账单详情失败', error);
    ElMessage.error('获取账单详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取账单状态类型
const getBillStatusType = (status) => {
  const statusMap = {
    'UNPAID': 'warning',
    'PAID': 'success',
    'OVERDUE': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取账单状态文本
const getBillStatusText = (status) => {
  const statusMap = {
    'UNPAID': '未支付',
    'PAID': '已支付',
    'OVERDUE': '已逾期'
  };
  return statusMap[status] || '未知';
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    'WECHAT': '微信支付',
    'ALIPAY': '支付宝支付',
    'BANK': '银行转账',
    'MOCK': '模拟支付'
  };
  return methodMap[method] || method;
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 判断是否逾期
const isOverdue = (dueDate) => {
  if (!dueDate) return false;
  return new Date(dueDate) < new Date();
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 查看协商详情
const viewNegotiationDetail = (negotiationId) => {
  router.push({
    path: `/advertiser/negotiation/${negotiationId}`
  });
};

// 处理支付操作
const handlePayBill = () => {
  paymentDialogVisible.value = true;
  selectedPaymentMethod.value = 'WECHAT'; // 默认选中微信支付
  qrCodeUrl.value = ''; // 重置二维码URL
  
  // 获取支付二维码
  generateQRCode();
};

// 生成支付二维码
const generateQRCode = async () => {
  try {
    console.log('正在生成支付二维码...');
    const res = await generatePaymentQRCode({
      billId: billId.value,
      paymentMethod: selectedPaymentMethod.value
    });
    
    console.log('支付二维码生成响应:', res);
    
    if (res.data.code === 200) {
      qrCodeUrl.value = res.data.data.qrCodeUrl;
      console.log('二维码URL已设置:', qrCodeUrl.value);
      
      // 启动轮询支付状态
      startCheckPaymentStatus();
      
      // 设置10秒后自动支付
      startAutoPayCountdown();
    } else {
      ElMessage.error(res.data.message || '生成支付二维码失败');
    }
  } catch (error) {
    console.error('生成支付二维码失败', error);
    ElMessage.error('生成支付二维码失败');
  }
};

// 开始检查支付状态
const startCheckPaymentStatus = () => {
  // 清除之前的定时器
  if (paymentCheckInterval.value) {
    clearInterval(paymentCheckInterval.value);
  }
  
  // 设置新的定时器，每3秒检查一次
  paymentCheckInterval.value = setInterval(async () => {
    try {
      const res = await checkPaymentStatus(billId.value);
      
      if (res.data.code === 200) {
        // 如果支付状态已变为已支付，关闭对话框并刷新
        if (res.data.data.status === 'PAID') {
          clearInterval(paymentCheckInterval.value);
          paymentDialogVisible.value = false;
          ElMessage.success('支付成功！');
          // 刷新账单数据
          fetchBillDetail();
        }
      }
    } catch (error) {
      console.error('检查支付状态失败', error);
    }
  }, 3000);
};

// 开始自动支付倒计时
const startAutoPayCountdown = () => {
  // 重置并清除之前的定时器
  clearTimeout(autoPayTimeout.value);
  clearInterval(countdownInterval.value);
  
  // 设置倒计时为10秒
  countdownSeconds.value = 10;
  
  // 更新倒计时
  countdownInterval.value = setInterval(() => {
    countdownSeconds.value -= 1;
    if (countdownSeconds.value <= 0) {
      clearInterval(countdownInterval.value);
    }
  }, 1000);
  
  // 10秒后自动调用模拟支付成功
  autoPayTimeout.value = setTimeout(() => {
    mockPaymentSuccess();
  }, 10000);
};

// 模拟支付成功
const mockPaymentSuccess = async () => {
  try {
    console.log('模拟支付成功被调用');
    const res = await mockApiSuccess(billId.value);
    
    if (res.data.code === 200) {
      clearInterval(paymentCheckInterval.value);
      clearInterval(countdownInterval.value);
      clearTimeout(autoPayTimeout.value);
      paymentDialogVisible.value = false;
      ElMessage.success('支付成功！');
      // 刷新账单数据
      fetchBillDetail();
    } else {
      ElMessage.error(res.data.message || '支付失败');
    }
  } catch (error) {
    console.error('模拟支付失败', error);
    ElMessage.error('支付失败');
  }
};

// 监听支付方式变化
watch(selectedPaymentMethod, () => {
  qrCodeUrl.value = ''; // 清空二维码
  countdownSeconds.value = 0; // 重置倒计时
  clearTimeout(autoPayTimeout.value); // 清除自动支付定时器
  clearInterval(countdownInterval.value); // 清除倒计时定时器
  generateQRCode(); // 重新生成二维码
});

// 监听对话框关闭
watch(paymentDialogVisible, (newVal) => {
  if (!newVal) {
    // 对话框关闭时清除定时器
    clearInterval(paymentCheckInterval.value);
    clearTimeout(autoPayTimeout.value);
    clearInterval(countdownInterval.value);
  }
});

onMounted(() => {
  fetchBillDetail();
});

onUnmounted(() => {
  // 组件卸载时清除所有定时器
  clearInterval(paymentCheckInterval.value);
  clearTimeout(autoPayTimeout.value);
  clearInterval(countdownInterval.value);
});
</script>

<style scoped>
.bill-detail-container {
  padding: 20px;
}

.detail-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.bill-info {
  padding: 10px 0;
}

.bill-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.bill-amount {
  text-align: right;
}

.amount-label {
  display: block;
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.amount-value {
  display: block;
  font-size: 32px;
  font-weight: bold;
  color: #F56C6C;
}

.info-section {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 120px;
  color: #606266;
  flex-shrink: 0;
}

.overdue {
  color: #F56C6C;
  font-weight: bold;
}

.payment-section {
  margin-top: 30px;
}

.payment-action {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 支付对话框样式 */
.payment-dialog-content {
  padding: 0 20px;
}

.payment-methods {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.payment-method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px;
  padding: 15px;
  border: 2px solid #EBEEF5;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method-item.active {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.method-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.method-icon.wechat {
  color: #07C160;
}

.method-icon.alipay {
  color: #1677FF;
}

.method-name {
  font-size: 14px;
  font-weight: bold;
}

.payment-amount {
  background-color: #f8f8f8;
  border-radius: 5px;
  padding: 15px;
  text-align: center;
  margin-bottom: 20px;
}

.amount-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.amount-value {
  color: #F56C6C;
  font-size: 24px;
  font-weight: bold;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.qrcode-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.qrcode {
  width: 200px;
  height: 200px;
  border: 1px solid #EBEEF5;
  padding: 5px;
  margin-bottom: 15px;
}

.qrcode img {
  width: 100%;
  height: 100%;
}

.qrcode-tip {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.loading-text {
  color: #909399;
  margin-top: 10px;
  font-size: 14px;
}

.iconfont {
  font-size: 32px;
}

.icon-wechat::before {
  content: "W";
  background-color: #07C160;
  color: white;
  padding: 5px;
  border-radius: 4px;
}

.icon-alipay::before {
  content: "A";
  background-color: #1677FF;
  color: white;
  padding: 5px;
  border-radius: 4px;
}

.auto-pay-countdown {
  width: 100%;
  margin-top: 15px;
}

.countdown-text {
  display: block;
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style>